import React from 'react'
import {
  inject,
  observer,
} from 'mobx-react'
import {
  Paper,
  List,
  ListItem,
  Card,
  CardHeader,
  CardActions,
  RaisedButton,
} from 'material-ui'
import axios from 'axios'
import './styles.css'
import { TopicStore } from '../../store/topic-store'
import * as utils from '../../util/utils'

const topicStore = new TopicStore()

@inject(stores => {
  return {
    topicStore,
  }
})
@observer
class Index extends React.Component {
  constructor() {
    super()
    this.fetchTopic = this.fetchTopic.bind(this)
    this.state = {
      userInfo: {}
    }
  }

  fetchTopic() {
    this.props.topicStore.fetchTopics()
  }

  goToTopic(topic) {
    this.props.history.push(`/detail/${topic.id}`)
  }

  parseTime(num) {
    return utils.parseTime(num)
  }

  getUserInfo = () => {
    // axios.get('http://10.73.39.8:3302/user/2').then(resp => {
    axios.get('http://127.0.0.1:3302/user/2').then(resp => {
      this.setState({
        userInfo: resp.data.data
      })
    })
  }

  componentDidMount() {
    this.fetchTopic()
    this.getUserInfo()
  }
  render() {
    const topics = this.props.topicStore.topics
    return (
      <Paper className="container">
        <div className="tags">
          <RaisedButton label="JavaScript" primary={true} />
          <RaisedButton label="前端" secondary={true} />
        </div>
        <div style={{backgroundColor: 'red', height: '50px', color: '#fff'}}>
          账号：{this.state.userInfo.username}
        </div>
        <List>
          {
            topics.map((topic, index) => {
              return (
                <ListItem
                  key={index}
                  onClick={() => this.goToTopic(topic)}
                >
                  <Card>
                    <CardHeader
                      title={topic.title}
                      subtitle={this.parseTime(topic.createTime)}
                    />
                    <CardActions style={{paddingBottom: '0'}}>
                      {
                        topic.tags && topic.tags.length > 0 && topic.tags.map((tag, tagIndex) => {
                          return (
                            <RaisedButton
                              label={tag.title}
                              primary={true}
                              style={{marginBottom: '8px'}}
                              key={tagIndex}
                            />
                          )
                        })
                      }
                    </CardActions>
                  </Card>
                </ListItem>
              )
            })
          }
        </List>
      </Paper>
    )
  }
}

export default Index
